package top.shiyiri.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author Aunean
 * @date 2022/1/28 17:34
 */
public class JDBCUtils {

    private static DataSource source = null;
    private static ThreadLocal<Connection> conns = new ThreadLocal<>();
    static {
        try {
            Properties props = new Properties();
            props.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
//            props.load(ClassLoader.getSystemResourceAsStream("jdbc.properties"));
            source = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        Connection conn = conns.get();
        if (conn == null) {
            try {
                conn = source.getConnection();//从数据库连接池中获取连接
                conns.set(conn);//保存到ThreadLocal对象中，供后面的JDBC操作管理
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return conn;
    }

    /**
     * 使用 dbutils中提供的DbUtils工具类，实现资源的关闭
     */
    public static void closeResource(Connection conn, Statement stmt, ResultSet rs) {
        DbUtils.closeQuietly(conn, stmt, rs);
    }

    public static void closeResource(Connection conn, Statement stmt) {
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(stmt);
    }

    public static void closeResource(Connection conn) {
        DbUtils.closeQuietly(conn);
    }

    /**
     * 提交事务，并关闭释放连接
     */
    public static void commitAndClose() {
        Connection connection = conns.get();
        if (connection != null) {
            try {
                connection.commit();//提交事务
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                closeResource(connection);//关闭连接
            }
        }
        conns.remove();
    }

    /**
     * 回滚事务，并关闭释放连接
     */
    public static void rollbackAndClose() {
        Connection connection = conns.get();
        if (connection != null) {
            try {
                connection.rollback();//回滚事务
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                closeResource(connection);//关闭连接
            }
        }
        conns.remove();
    }
}
